package leetcode.N101_N200;

import com.huwaiwai001.netty.nio.NIOClient;
import leetcode.comm.Node;

/**
 * @author xiwai [hww282306@alibaba-inc.com]
 * @version 1.0
 * @date 2020/10/15 7:22 下午
 */
public class N116 {

    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        Node node7 = new Node(7);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;

        connect(node1);
    }

    public static Node connect(Node root) {
        Node current = root;
        while (current != null) {
            linkNode(current);
            current = current.left;
        }
        return root;
    }

    private static void linkNode(Node root) {
        Node next = root;
        Node lastRight = null;
        while (next != null && next.left != null) {
            Node right = next.right;
            Node left = next.left;
            // 链接
            if (lastRight != null) {
                lastRight.next = left;
            }
            left.next = right;
            lastRight = right;
            next = next.next;
        }
    }

}
